package secondriver.springsubway.demo.editor;

import java.beans.PropertyEditorSupport;

import org.springframework.util.StringUtils;

public class PasswordPropertyEditor extends PropertyEditorSupport {

	private static final String DEFAULT_PREFIX = "PWD[";
	private static final String DEFAULT_SUBFIX = "]";

	private String prefix;

	private String suffix;

	public PasswordPropertyEditor() {
		this(DEFAULT_PREFIX, DEFAULT_SUBFIX);
	}

	public PasswordPropertyEditor(String prefix, String suffix) {
		this.prefix = prefix;
		this.suffix = suffix;
	}

	@Override
	public String getAsText() {
		return this.prefix + getValue() + this.suffix;
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		Password password = new Password();

		if (StringUtils.isEmpty(text)) {
			setValue(password);
			return;
		}
		if (text.startsWith(prefix) && text.endsWith(suffix)) {
			password.setCipherText(text);
			String plainText = text.substring(prefix.length(),
					(text.length() - suffix.length()));
			password.setPlainText(plainText);
		} else {
			password.setPlainText(text);
			String cipherText = prefix + text + suffix;
			password.setCipherText(cipherText);
		}
		setValue(password);
	}

	public String getPrefix() {
		return this.prefix;
	}

	public String getSuffix() {
		return this.suffix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}

}
